package com.example.myapplication;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.Settings;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import java.io.File;

/**
 * 软件更新Activity
 * 支持应用、固件、后端三种类型的更新
 */
public class SoftwareUpdateActivity extends AppCompatActivity {

    private UpdateService updateService;
    private SystemControlService systemControlService;

    // App更新相关
    private TextView textAppVersion;
    private TextView textAppContent;
    private ProgressBar progressAppDownload;
    private TextView textAppProgress;
    private Button btnAppCheck;
    private Button btnAppDownload;
    private Button btnAppInstall;
    private VersionInfo appVersionInfo;
    private String appDownloadPath;

    // Firmware更新相关
    private TextView textFirmwareVersion;
    private TextView textFirmwareContent;
    private ProgressBar progressFirmwareDownload;
    private TextView textFirmwareProgress;
    private Button btnFirmwareCheck;
    private Button btnFirmwareDownload;
    private Button btnFirmwareInstall;
    private VersionInfo firmwareVersionInfo;
    private String firmwareDownloadPath;

    // Server更新相关
    private TextView textServerVersion;
    private TextView textServerContent;
    private ProgressBar progressServerDownload;
    private TextView textServerProgress;
    private Button btnServerCheck;
    private Button btnServerDownload;
    private Button btnServerInstall;
    private VersionInfo serverVersionInfo;
    private String serverDownloadPath;

    private Handler mainHandler;
    private static final int REQUEST_INSTALL_PERMISSION = 1001;
    private String pendingInstallPath; // 待安装的文件路径

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_software_update);

        updateService = new UpdateService(this);
        systemControlService = new SystemControlService(this);
        mainHandler = new Handler(Looper.getMainLooper());

        initViews();
        setupListeners();

        // 自动检查所有更新
        checkAllUpdates();
    }
    
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_INSTALL_PERMISSION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 权限已授予，可以继续安装
                Toast.makeText(this, "安装权限已授予", Toast.LENGTH_SHORT).show();
            } else {
                // 权限被拒绝，引导用户到设置页面
                Toast.makeText(this, "需要安装权限才能安装应用", Toast.LENGTH_LONG).show();
            }
        }
    }

    private void initViews() {
        // App更新视图
        textAppVersion = findViewById(R.id.text_app_version);
        textAppContent = findViewById(R.id.text_app_content);
        progressAppDownload = findViewById(R.id.progress_app_download);
        textAppProgress = findViewById(R.id.text_app_progress);
        btnAppCheck = findViewById(R.id.btn_app_check);
        btnAppDownload = findViewById(R.id.btn_app_download);
        btnAppInstall = findViewById(R.id.btn_app_install);

        // Firmware更新视图
        textFirmwareVersion = findViewById(R.id.text_firmware_version);
        textFirmwareContent = findViewById(R.id.text_firmware_content);
        progressFirmwareDownload = findViewById(R.id.progress_firmware_download);
        textFirmwareProgress = findViewById(R.id.text_firmware_progress);
        btnFirmwareCheck = findViewById(R.id.btn_firmware_check);
        btnFirmwareDownload = findViewById(R.id.btn_firmware_download);
        btnFirmwareInstall = findViewById(R.id.btn_firmware_install);

        // Server更新视图
        textServerVersion = findViewById(R.id.text_server_version);
        textServerContent = findViewById(R.id.text_server_content);
        progressServerDownload = findViewById(R.id.progress_server_download);
        textServerProgress = findViewById(R.id.text_server_progress);
        btnServerCheck = findViewById(R.id.btn_server_check);
        btnServerDownload = findViewById(R.id.btn_server_download);
        btnServerInstall = findViewById(R.id.btn_server_install);
    }

    private void setupListeners() {
        // App更新按钮
        btnAppCheck.setOnClickListener(v -> checkUpdate("app", "app"));
        btnAppDownload.setOnClickListener(v -> downloadUpdate("app", appVersionInfo));
        btnAppInstall.setOnClickListener(v -> installApk(appDownloadPath));

        // Firmware更新按钮
        btnFirmwareCheck.setOnClickListener(v -> checkUpdate("firmware", "firmware"));
        btnFirmwareDownload.setOnClickListener(v -> downloadUpdate("firmware", firmwareVersionInfo));
        btnFirmwareInstall.setOnClickListener(v -> installApk(firmwareDownloadPath));

        // Server更新按钮
        btnServerCheck.setOnClickListener(v -> checkUpdate("server", "server"));
        btnServerDownload.setOnClickListener(v -> downloadUpdate("server", serverVersionInfo));
        btnServerInstall.setOnClickListener(v -> installApk(serverDownloadPath));
    }

    private void checkAllUpdates() {
        checkUpdate("app", "app");
        checkUpdate("firmware", "firmware");
        checkUpdate("server", "server");
    }

    private void checkUpdate(String type, String deviceType) {
        TextView textVersion = getVersionTextView(type);
        TextView textContent = getContentTextView(type);
        Button btnDownload = getDownloadButton(type);
        Button btnInstall = getInstallButton(type);

        textVersion.setText("检查中...");
        textContent.setVisibility(View.GONE);
        btnDownload.setVisibility(View.GONE);
        btnInstall.setVisibility(View.GONE);

        updateService.checkVersion(deviceType, new UpdateService.VersionCheckCallback() {
            @Override
            public void onSuccess(VersionInfo versionInfo) {
                mainHandler.post(() -> {
                    String versionText = "版本: " + versionInfo.getVersion();
                    if (versionInfo.getVersionCode() > 0) {
                        versionText += " (Code: " + versionInfo.getVersionCode() + ")";
                    }
                    if (versionInfo.getFileSize() > 0) {
                        versionText += "\n文件大小: " + versionInfo.getFormattedFileSize();
                    }
                    if (versionInfo.getUpdateTime() != null && !versionInfo.getUpdateTime().isEmpty()) {
                        versionText += "\n更新时间: " + versionInfo.getUpdateTime();
                    }
                    textVersion.setText(versionText);

                    if (versionInfo.getUpdateContent() != null && !versionInfo.getUpdateContent().isEmpty()) {
                        textContent.setText(versionInfo.getUpdateContent());
                        textContent.setVisibility(View.VISIBLE);
                    }

                    btnDownload.setVisibility(View.VISIBLE);
                    saveVersionInfo(type, versionInfo);

                    // 如果有更新内容，显示更新对话框
                    if (versionInfo.getUpdateContent() != null && !versionInfo.getUpdateContent().isEmpty()) {
                        showUpdateDialog(type, versionInfo);
                    } else {
                        // 检查是否需要强制更新
                        if (versionInfo.isForceUpdate()) {
                            Toast.makeText(SoftwareUpdateActivity.this, 
                                    "发现强制更新，请尽快更新", Toast.LENGTH_LONG).show();
                        }
                    }
                });
            }

            @Override
            public void onError(String error) {
                mainHandler.post(() -> {
                    textVersion.setText("检查失败: " + error);
                    Toast.makeText(SoftwareUpdateActivity.this, "检查更新失败: " + error, Toast.LENGTH_SHORT).show();
                });
            }
        });
    }

    private void downloadUpdate(String type, VersionInfo versionInfo) {
        if (versionInfo == null) {
            Toast.makeText(this, "请先检查更新", Toast.LENGTH_SHORT).show();
            return;
        }

        ProgressBar progressBar = getProgressBar(type);
        TextView textProgress = getProgressTextView(type);
        Button btnDownload = getDownloadButton(type);
        Button btnInstall = getInstallButton(type);

        progressBar.setVisibility(View.VISIBLE);
        progressBar.setProgress(0);
        textProgress.setVisibility(View.VISIBLE);
        textProgress.setText("0%");
        btnDownload.setEnabled(false);

        updateService.downloadFile(versionInfo, new UpdateService.DownloadCallback() {
            @Override
            public void onProgress(int progress, long downloaded, long total) {
                mainHandler.post(() -> {
                    progressBar.setProgress(progress);
                    textProgress.setText(String.format("%d%% (%.2f MB / %.2f MB)", 
                            progress, downloaded / 1024.0 / 1024.0, total / 1024.0 / 1024.0));
                });
            }

            @Override
            public void onResume(long downloadedSize) {
                mainHandler.post(() -> {
                    textProgress.setText(String.format("断点续传: 已下载 %.2f MB", 
                            downloadedSize / 1024.0 / 1024.0));
                    Toast.makeText(SoftwareUpdateActivity.this, 
                            "检测到未完成的下载，继续下载...", Toast.LENGTH_SHORT).show();
                });
            }

            @Override
            public void onRetry(int retryCount, int maxRetryCount, String error) {
                mainHandler.post(() -> {
                    String retryText = String.format("网络错误，正在重试 (%d/%d)...", 
                            retryCount, maxRetryCount);
                    textProgress.setText(retryText);
                    Toast.makeText(SoftwareUpdateActivity.this, 
                            retryText + "\n错误: " + error, Toast.LENGTH_LONG).show();
                });
            }

            @Override
            public void onSuccess(String filePath) {
                mainHandler.post(() -> {
                    progressBar.setVisibility(View.GONE);
                    textProgress.setVisibility(View.GONE);
                    btnDownload.setVisibility(View.GONE);
                    btnDownload.setEnabled(true);
                    saveDownloadPath(type, filePath);
                    Toast.makeText(SoftwareUpdateActivity.this, "下载完成，正在安装...", Toast.LENGTH_SHORT).show();
                    
                    // 下载完成后自动安装
                    installApk(filePath);
                });
            }

            @Override
            public void onError(String error) {
                mainHandler.post(() -> {
                    progressBar.setVisibility(View.GONE);
                    textProgress.setVisibility(View.GONE);
                    btnDownload.setEnabled(true);
                    btnDownload.setVisibility(View.VISIBLE);
                    Toast.makeText(SoftwareUpdateActivity.this, "下载失败: " + error, Toast.LENGTH_LONG).show();
                });
            }
        });
    }

    /**
     * 显示更新内容对话框
     */
    private void showUpdateDialog(String type, VersionInfo versionInfo) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("发现新版本 " + versionInfo.getVersion());
        
        // 创建滚动文本视图显示更新内容
        TextView textView = new TextView(this);
        textView.setPadding(50, 40, 50, 40);
        textView.setText(versionInfo.getUpdateContent());
        textView.setTextSize(14);
        textView.setLineSpacing(0, 1.2f);
        
        // 设置滚动视图
        android.widget.ScrollView scrollView = new android.widget.ScrollView(this);
        scrollView.addView(textView);
        
        // 通过LayoutParams设置最大高度
        android.widget.LinearLayout.LayoutParams params = new android.widget.LinearLayout.LayoutParams(
                android.widget.LinearLayout.LayoutParams.MATCH_PARENT,
                android.widget.LinearLayout.LayoutParams.WRAP_CONTENT);
        params.height = (int) (getResources().getDisplayMetrics().heightPixels * 0.6); // 屏幕高度的60%
        scrollView.setLayoutParams(params);
        
        builder.setView(scrollView);
        
        builder.setPositiveButton("立即更新", (dialog, which) -> {
            // 点击确定后开始下载
            downloadUpdate(type, versionInfo);
            dialog.dismiss();
        });
        
        builder.setNegativeButton("稍后更新", (dialog, which) -> {
            dialog.dismiss();
        });
        
        // 如果是强制更新，只显示确定按钮
        if (versionInfo.isForceUpdate()) {
            builder.setCancelable(false);
            builder.setNegativeButton(null, null);
        }
        
        builder.show();
    }
    
    private void installApk(String filePath) {
        if (filePath == null || filePath.isEmpty()) {
            Toast.makeText(this, "请先下载安装包", Toast.LENGTH_SHORT).show();
            return;
        }

        File file = new File(filePath);
        if (!file.exists()) {
            Toast.makeText(this, "安装包文件不存在", Toast.LENGTH_SHORT).show();
            return;
        }

        // Android 8.0+ 需要动态请求安装权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            if (!getPackageManager().canRequestPackageInstalls()) {
                // 没有安装权限，保存文件路径，请求权限
                pendingInstallPath = filePath;
                Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
                intent.setData(Uri.parse("package:" + getPackageName()));
                startActivityForResult(intent, REQUEST_INSTALL_PERMISSION);
                Toast.makeText(this, "请授予安装权限", Toast.LENGTH_LONG).show();
                return;
            }
        }

        try {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            Uri uri;
            
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                // Android 7.0+ 使用FileProvider
                String authority = getApplicationContext().getPackageName() + ".fileprovider";
                uri = FileProvider.getUriForFile(this, authority, file);
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            } else {
                // Android 7.0以下直接使用file://
                uri = Uri.fromFile(file);
            }
            
            intent.setDataAndType(uri, "application/vnd.android.package-archive");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            
            Toast.makeText(this, "正在安装...", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Toast.makeText(this, "安装失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            // 备用方案：使用SystemControlService安装
            SystemControlService.SystemControlResult result = systemControlService.installApk(filePath);
            if (!result.success) {
                Toast.makeText(this, "安装失败: " + result.message, Toast.LENGTH_SHORT).show();
            }
        }
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_INSTALL_PERMISSION) {
            // 用户从设置页面返回，检查权限是否已授予
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                if (getPackageManager().canRequestPackageInstalls()) {
                    // 权限已授予，自动安装之前保存的文件
                    if (pendingInstallPath != null && !pendingInstallPath.isEmpty()) {
                        String path = pendingInstallPath;
                        pendingInstallPath = null; // 清空待安装路径
                        // 延迟一下，确保权限已生效
                        mainHandler.postDelayed(() -> installApk(path), 300);
                    } else {
                        Toast.makeText(this, "安装权限已授予", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(this, "安装权限未授予，无法安装", Toast.LENGTH_LONG).show();
                }
            }
        }
    }

    // 获取视图的辅助方法
    private TextView getVersionTextView(String type) {
        switch (type) {
            case "app": return textAppVersion;
            case "firmware": return textFirmwareVersion;
            case "server": return textServerVersion;
            default: return null;
        }
    }

    private TextView getContentTextView(String type) {
        switch (type) {
            case "app": return textAppContent;
            case "firmware": return textFirmwareContent;
            case "server": return textServerContent;
            default: return null;
        }
    }

    private ProgressBar getProgressBar(String type) {
        switch (type) {
            case "app": return progressAppDownload;
            case "firmware": return progressFirmwareDownload;
            case "server": return progressServerDownload;
            default: return null;
        }
    }

    private TextView getProgressTextView(String type) {
        switch (type) {
            case "app": return textAppProgress;
            case "firmware": return textFirmwareProgress;
            case "server": return textServerProgress;
            default: return null;
        }
    }

    private Button getDownloadButton(String type) {
        switch (type) {
            case "app": return btnAppDownload;
            case "firmware": return btnFirmwareDownload;
            case "server": return btnServerDownload;
            default: return null;
        }
    }

    private Button getInstallButton(String type) {
        switch (type) {
            case "app": return btnAppInstall;
            case "firmware": return btnFirmwareInstall;
            case "server": return btnServerInstall;
            default: return null;
        }
    }

    private void saveVersionInfo(String type, VersionInfo versionInfo) {
        switch (type) {
            case "app": appVersionInfo = versionInfo; break;
            case "firmware": firmwareVersionInfo = versionInfo; break;
            case "server": serverVersionInfo = versionInfo; break;
        }
    }

    private void saveDownloadPath(String type, String filePath) {
        switch (type) {
            case "app": appDownloadPath = filePath; break;
            case "firmware": firmwareDownloadPath = filePath; break;
            case "server": serverDownloadPath = filePath; break;
        }
    }
}

